const express = require("express");
const chatUserRouter = express.Router();
const pool = require("../pool.js");
// 导入生成Token的包
const jwt = require("jsonwebtoken");
// 导入全局配置文件（里面有token的密钥）
const config = require("../config.js");
// 将数据库的字段名转换为驼峰命名
const _ = require("lodash");
// 生成随机字符串uid
const uuid = require("node-uuid");
const { wsList } = require("./ws.js");
const { checkToken } = require("../utils/token.js");
const { GroupType } = require("../enum/group.js");
// var uid = uuid.v1();
// var uidv4 = uuid.v4();

// 注册接口
chatUserRouter.post("/register", (req, res) => {
  if (req.body.username.trim() === "" || req.body.password.trim() === "") {
    res.send({
      code: 400,
      message: "用户名或密码不能为空",
    });
    return;
  }
  pool.query(
    "SELECT * FROM chat_user WHERE user_name = ?",
    [req.body.username],
    (err, results) => {
      if (err) throw err;
      if (results.length > 0) {
        res.send({
          code: 401,
          message: "用户名已存在，请重新输入",
        });
        return;
      } else {
        pool.query(
          "INSERT INTO chat_user SET ?",
          {
            user_name: req.body.username,
            user_pwd: req.body.password,
            uid: uuid.v1().replace(/\-/g, ""),
          },
          (err, results) => {
            if (err) throw err;
            res.send({
              code: 200,
              message: "注册成功",
            });
          }
        );
      }
    }
  );
});

// 登录接口
chatUserRouter.post("/login", (req, res) => {
  if (req.body.username.trim() === "" || req.body.password.trim() === "") {
    res.send({
      code: 402,
      message: "用户名或密码不能为空",
    });
    return;
  }
  pool.query(
    "SELECT * FROM chat_user WHERE user_name = ?",
    [req.body.username],
    (err, results) => {
      if (results.length === 0) {
        res.send({
          code: 400,
          message: "账号不存在，请先注册",
        });
      } else {
        pool.query(
          "SELECT * FROM chat_user WHERE user_name = ? AND user_pwd = ?",
          [req.body.username, req.body.password],
          (err, results, fields) => {
            if (err) throw err;
            if (results.length > 0) {
              // 在服务器端生成 Token 字符串
              const user = {
                ...results[0], // 解构用户信息
                user_pwd: "", //密码等敏感信息置空
              };
              // 对用户的信息进行加密，生成 token 字符串 jwt.sign
              const tokenStr = jwt.sign(user, config.jwtSecretKey, {
                expiresIn: config.expiresIn, //tonken 有效期
              });
              // 将数据库的字段名转换为驼峰命名
              const convertedResponse = _.mapKeys(user, (value, key) =>
                _.camelCase(key)
              );
              res.send({
                code: 200,
                data: {
                  user: convertedResponse,
                  token: tokenStr,
                },
                message: "登录成功",
              });
              // 登录成功后，将用户token保存
              pool.query(
                "SELECT * FROM chat_user_token WHERE user_name = ?",
                [user.user_name],
                (err, results) => {
                  if (err) throw err;
                  if (results.length > 0) {
                    pool.query(
                      "UPDATE chat_user_token SET user_token = ? WHERE user_name = ?",
                      [tokenStr, user.user_name],
                      (err, results) => {
                        if (err) throw err;
                      }
                    );
                  } else {
                    pool.query(
                      "INSERT INTO chat_user_token SET ?",
                      {
                        user_name: user.user_name,
                        user_token: tokenStr,
                      },
                      (err, results) => {
                        if (err) throw err;
                      }
                    );
                  }
                }
              );
            } else {
              res.send({
                code: 401,
                message: "账号或者密码错误",
              });
            }
          }
        );
      }
    }
  );
});

// 根据用户上传的头像地址，存储头像到服务器
chatUserRouter.post("/uploadAvatar", (req, res) => {
  const token = req.headers.authorization.split(" ")[1];
  // 验证 token jwt.verify解码token
  jwt.verify(token, config.jwtSecretKey, (err, decoded) => {
    if (err) {
      res.send({
        code: 401,
        message: "token 验证失败，请重新登录",
      });
    } else {
      pool.query(
        "UPDATE chat_user SET user_avatar = ? WHERE user_name = ?",
        [req.body.avatarUrl, req.body.username],
        (err, results) => {
          if (err) throw err;
          if (results.affectedRows === 1) {
            res.send({
              code: 200,
              message: "头像上传成功",
            });
          } else {
            res.send({
              code: 400,
              message: "头像上传失败",
            });
          }
        }
      );
    }
  });
});

// 创建群聊接口
chatUserRouter.post("/createGroup", (req, res) => {
  const token = req.headers.authorization.split(" ")[1];

  // 验证 token jwt.verify解码token
  jwt.verify(token, config.jwtSecretKey, (err, decoded) => {
    if (err) {
      res.send({
        code: 401,
        message: "token 验证失败，请重新登录",
      });
    } else {
      const group_uid = uuid.v1().replace(/\-/g, "");
      pool.query(
        "INSERT INTO chat_group SET ?",
        {
          group_name: req.body.groupName,
          group_avatar: req.body.groupAvatar,
          group_desc: req.body.groupDesc,
          group_owner: decoded.uid,
          group_type: req.body.groupType,
          group_uid,
        },
        (err, results) => {
          if (err) throw err;
          if (results.affectedRows === 1) {
            res.send({
              code: 200,
              data: {
                chatId: group_uid,
              },
              message: "群聊创建成功",
            });
          } else {
            res.send({
              code: 400,
              message: "群聊创建失败",
            });
          }
        }
      );
    }
  });
});

// 获取群聊列表接口
chatUserRouter.get("/getGroupList", (req, res) => {
  const token = req.headers.authorization.split(" ")[1];
  // 验证 token jwt.verify解码token
  jwt.verify(token, config.jwtSecretKey, (err, decoded) => {
    if (err) {
      res.send({
        code: 401,
        message: "token 验证失败，请重新登录",
      });
    } else {
      pool.query(
        "SELECT * FROM chat_group WHERE group_owner = ?",
        [decoded.user_name],
        (err, results) => {
          if (err) throw err;
          if (results.length > 0) {
            const convertedResponse = _.mapKeys(results, (value, key) =>
              _.camelCase(key)
            );
            res.send({
              code: 200,
              data: {
                groupList: convertedResponse,
              },
              message: "获取群聊列表成功",
            });
          } else {
            res.send({
              code: 400,
              message: "获取群聊列表失败",
            });
          }
        }
      );
    }
  });
});

// 获取群聊成员列表接口
chatUserRouter.get("/getGroupMemberList/:groupId", (req, res) => {
  const token = req.headers.authorization.split(" ")[1];
  // 验证 token jwt.verify解码token
  jwt.verify(token, config.jwtSecretKey, (err, decoded) => {
    if (err) {
      res.send({
        code: 401,
        message: "token 验证失败，请重新登录",
      });
    } else {
      pool.query(
        "SELECT * FROM chat_group_member WHERE group_id = ?",
        [req.params.groupId],
        (err, results) => {
          if (err) throw err;
          if (results.length > 0) {
            const convertedResponse = _.mapKeys(results, (value, key) =>
              _.camelCase(key)
            );
            res.send({
              code: 200,
              data: {
                groupMemberList: convertedResponse,
              },
              message: "获取群聊成员列表成功",
            });
          } else {
            res.send({
              code: 400,
              message: "获取群聊成员列表失败",
            });
          }
        }
      );
    }
  });
});

// 加入群聊接口
chatUserRouter.post("/joinGroup", (req, res) => {
  const token = req.headers.authorization.split(" ")[1];
  // 验证 token jwt.verify解码token
  jwt.verify(token, config.jwtSecretKey, (err, decoded) => {
    if (err) {
      res.send({
        code: 401,
        message: "token 验证失败，请重新登录",
      });
    } else {
      pool.query(
        "INSERT INTO chat_group_member SET ?",
        {
          group_id: req.body.groupId,
          user_name: decoded.user_name,
          user_avatar: decoded.user_avatar,
          user_uid: decoded.uid,
        },
        (err, results) => {
          if (err) throw err;
          if (results.affectedRows === 1) {
            res.send({
              code: 200,
              message: "加入群聊成功",
            });
          } else {
            res.send({
              code: 400,
              message: "加入群聊失败",
            });
          }
        }
      );
    }
  });
});

// 退出群聊接口
chatUserRouter.post("/quitGroup", (req, res) => {
  const token = req.headers.authorization.split(" ")[1];
  // 验证 token jwt.verify解码token
  jwt.verify(token, config.jwtSecretKey, (err, decoded) => {
    if (err) {
      res.send({
        code: 401,
        message: "token 验证失败，请重新登录",
      });
    } else {
      pool.query(
        "DELETE FROM chat_group_member WHERE group_id = ? AND user_name = ?",
        [req.body.groupId, decoded.user_name],
        (err, results) => {
          if (err) throw err;
          if (results.affectedRows === 1) {
            res.send({
              code: 200,
              message: "退出群��成功",
            });
          } else {
            res.send({
              code: 400,
              message: "退出群聊失败",
            });
          }
        }
      );
    }
  });
});

// 获取好友列表
chatUserRouter.get("/getFriendList", (req, res) => {
  const token = req.headers.authorization.split(" ")[1];
  // 验证 token jwt.verify解码token
  jwt.verify(token, config.jwtSecretKey, (err, decoded) => {
    if (err) {
      res.send({
        code: 401,
        message: "token 验证失败，请重新登录",
      });
    } else {
      pool.query(
        "SELECT * FROM chat_friend WHERE user_id = ? OR friend_id = ?",
        [decoded.uid, decoded.uid],
        (err, results) => {
          if (err) throw err;
          if (results.length > 0) {
            const friendList = results.map((friend) => {
              const convertedResponse = _.mapKeys(friend, (value, key) =>
                _.camelCase(key)
              );
              return convertedResponse;
            });
            res.send({
              code: 200,
              data: {
                friendList: friendList,
              },
              message: "获取好友列表成功",
            });
          } else {
            res.send({
              code: 400,
              data: [],
              message: "暂无好友",
            });
          }
        }
      );
    }
  });
});

// 发起好友申请接口
chatUserRouter.post("/addFriend", (req, res) => {
  const token = req.headers.authorization.split(" ")[1];
  // 验证 token jwt.verify解码token
  jwt.verify(token, config.jwtSecretKey, (err, decoded) => {
    if (err) {
      res.send({
        code: 401,
        message: "token 验证失败，请重新登录",
      });
    } else {
      wsList.forEach((ws) => {
        if (ws.id === req.body.friendId) {
          ws.send(
            JSON.stringify({
              type: "notice",
              msgType: "friendRequest",
              msg: "好友请求申请",
              data: {
                fromId: decoded.uid,
                toId: req.body.friendId,
                fromName: decoded.user_name,
                toName: req.body.friendName,
              },
            })
          );
        }
      });
      res.send({
        code: 200,
        message: "发送好友请求成功",
      });
    }
  });
});

// 同意好友申请接口
chatUserRouter.post("/agreeFriend", (req, res) => {
  const token = req.headers.authorization.split(" ")[1];
  // 验证 token jwt.verify解码token
  jwt.verify(token, config.jwtSecretKey, (err, decoded) => {
    if (err) {
      res.send({
        code: 401,
        message: "token 验证失败，请重新登录",
      });
    } else {
      pool.query(
        "INSERT INTO chat_friend SET ?",
        {
          user_id: decoded.uid,
          friend_id: req.body.friendId,
        },
        (err, results) => {
          if (err) throw err;
          if (results.affectedRows === 1) {
            res.send({
              code: 200,
              message: "添加好友成功",
            });
          } else {
            res.send({
              code: 400,
              message: "添加好友失败",
            });
          }
        }
      );
    }
  });
});

// 查询个人信息

chatUserRouter.get("/getUserInfo", (req, res) => {
  const token = req.headers.authorization.split(" ")[1];
  // 验证 token jwt.verify解码token
  jwt.verify(token, config.jwtSecretKey, (err, decoded) => {
    if (err) {
      res.send({
        code: 401,
        message: "token 验证失败，请重新登录",
      });
    } else {
      pool.query(
        "SELECT * FROM chat_user WHERE user_name = ?",
        [req.query.username],
        (err, results) => {
          if (err) throw err;
          if (results.length > 0) {
            const user = {
              ...results[0], // 解构用户信息
              user_pwd: "", //密码等敏感信息置空
            };
            const convertedResponse = _.mapKeys(user, (value, key) =>
              _.camelCase(key)
            );
            res.send({
              code: 200,
              data: {
                userInfo: convertedResponse,
              },
              message: "获取个人信息成功",
            });
          } else {
            res.send({
              code: 400,
              message: "获取个人信息失败",
            });
          }
        }
      );
    }
  });
});

// 模糊匹配用户接口

chatUserRouter.get("/searchUser", (req, res) => {
  const token = req.headers.authorization.split(" ")[1];
  // 验证 token jwt.verify解码token
  jwt.verify(token, config.jwtSecretKey, (err, decoded) => {
    if (err) {
      res.send({
        code: 401,
        message: "token 验证失败，请重新登录",
      });
    } else {
      pool.query(
        "SELECT * FROM chat_user WHERE user_name LIKE ?",
        [`%${req.query.keyword}%`],
        (err, results) => {
          if (err) throw err;
          if (results.length > 0) {
            const userList = results.map((user) => {
              user.user_pwd = ""; //密码等敏感信息置空
              const convertedResponse = _.mapKeys(user, (value, key) =>
                _.camelCase(key)
              );
              return convertedResponse;
            });
            res.send({
              code: 200,
              data: {
                userList: userList,
              },
              message: "模糊匹配用户成功",
            });
          } else {
            res.send({
              code: 400,
              data: [],
              message: "没有匹配的用户",
            });
          }
        }
      );
    }
  });
});

// 判断是否为好友接口

chatUserRouter.get("/isFriend", (req, res) => {
  const token = req.headers.authorization.split(" ")[1];
  // 验证 token jwt.verify解码token
  jwt.verify(token, config.jwtSecretKey, (err, decoded) => {
    if (err) {
      res.send({
        code: 401,
        message: "token 验证失败，请重新登录",
      });
    } else {
      pool.query(
        "SELECT * FROM chat_friend WHERE user_id = ? AND friend_id = ? OR friend_id = ? AND user_id = ?",
        [decoded.uid, req.query.friendId, decoded.uid, req.query.friendId],
        (err, results) => {
          if (err) throw err;
          if (results.length > 0) {
            res.send({
              code: 200,
              data: {
                isFriend: true,
              },
              message: "已是好友",
            });
          } else {
            res.send({
              code: 400,
              data: {
                isFriend: false,
              },
              message: "不是好友",
            });
          }
        }
      );
    }
  });
});

// 根据用户传入的多个id，获取多个用户信息接口

chatUserRouter.post("/getUserList", (req, res) => {
  const token = req.headers.authorization.split(" ")[1];
  // 验证 token jwt.verify解码token
  jwt.verify(token, config.jwtSecretKey, (err, decoded) => {
    if (err) {
      res.send({
        code: 401,
        message: "token 验证失败，请重新登录",
      });
    } else {
      pool.query(
        "SELECT * FROM chat_user WHERE uid IN (?)",
        [req.body.userIdList],
        (err, results) => {
          if (err) throw err;
          if (results.length > 0) {
            const userList = results.map((user) => {
              user.user_pwd = ""; //密码等敏感信息置空
              const convertedResponse = _.mapKeys(user, (value, key) =>
                _.camelCase(key)
              );
              return convertedResponse;
            });
            res.send({
              code: 200,
              data: {
                userList: userList,
              },
              message: "获取多个用户信息成功",
            });
          } else {
            res.send({
              code: 400,
              data: [],
              message: "没有匹配的用户",
            });
          }
        }
      );
    }
  });
});

// 导出路由
module.exports = chatUserRouter;
